//
//  UITextView+Extension.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//

import UIKit

extension UITextInput {
    /// 根据坐标，获取textView富文本的info
    public func textStyling(at point: CGPoint) -> [NSAttributedString.Key : Any]? {
        guard let position = self.closestPosition(to: point),
              let info = self.textStyling?(at: position, in: .forward) else {
            return nil
        }
        return info
    }
    
    /// 获取坐标，获取textView的
    public func link(at point: CGPoint) -> String? {
        guard let info = textStyling(at: point) else {
            return nil
        }
        return info[NSAttributedString.Key.link] as? String
    }
}

extension UITextInput {
    
    // 输入框中标记文本的范围
    public var markedTextNSRange: NSRange? {
        guard let markedTextRange = markedTextRange else { return nil }
        let location = offset(from: beginningOfDocument, to: markedTextRange.start)
        let length = offset(from: markedTextRange.start, to: markedTextRange.end)
        return NSRange(location: location, length: length)
    }
    
    /// 输出框中不包含标记的文本
    /// 不包含标记文本的前后部分，如果标记文本在输入框最后，则只有前面front那部分，back为空
    public var nonMarkedText: (front: String, back: String) {
        let start = beginningOfDocument
        let end = endOfDocument
        
        guard let rangeAll = textRange(from: start, to: end),
              let text = text(in: rangeAll) else {
                  return ("", "")
              }
        
        guard let markedTextRange = markedTextRange else {
            return (text, "")
        }
        
        guard let startRange = textRange(from: start, to: markedTextRange.start),
              let endRange = textRange(from: markedTextRange.end, to: end) else {
                  return (text, "")
              }
        return (self.text(in: startRange) ?? "", self.text(in: endRange) ?? "")
    }
}
